{% extends "admin/change_form.html" %}

{% block object-tools-items %}
  {{ block.super }}
  <li>
    <a href="{% url 'admin:auth_user_changelist' %}" class="button">返回用户列表</a>
  </li>
{% endblock %}

{% block submit_buttons_bottom %}
  {{ block.super }}
  {% if original %}
  <div class="inline-group" style="margin-top: 20px;">
    <fieldset class="module aligned">
      <h2>上传头像</h2>
      <div>
        <input type="file" id="admin-avatar-file" accept="image/*">
        <button type="button" class="button" id="admin-avatar-upload-btn">上传到COS</button>
      </div>
      <p class="help">支持 JPEG、PNG、GIF、WebP，最大 5MB</p>
    </fieldset>
  </div>
  <script>
    (function(){
      const btn = document.getElementById('admin-avatar-upload-btn')
      const fileInput = document.getElementById('admin-avatar-file')
      if (!btn || !fileInput) return
      btn.addEventListener('click', function(){
        const file = fileInput.files && fileInput.files[0]
        if (!file) { alert('请选择头像文件'); return }
        const allowed = ['image/jpeg','image/png','image/gif','image/webp']
        if (allowed.indexOf(file.type) === -1) { alert('文件格式不支持'); return }
        if (file.size > 5 * 1024 * 1024) { alert('文件大小不能超过5MB'); return }
        const fd = new FormData()
        fd.append('avatar', file)
        const url = '/xiangsu/upload/avatar/?user_id={{ original.id }}'
        fetch(url, { method: 'POST', body: fd, credentials: 'same-origin' })
          .then(r => r.json())
          .then(d => { if (d.success) { alert('上传成功'); location.reload() } else { alert('上传失败: ' + (d.message||'')) } })
          .catch(e => alert('上传出错: ' + e))
      })
    })()
  </script>
  {% else %}
  <p class="help">保存用户后可上传头像</p>
  {% endif %}
{% endblock %}